#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "clientsocket.h"
#include <QThread>
#include <QList>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->port->setText("8899");
    //初始化账号密码
    username.append("孤独的狼");
    passward.append("123456");
    username.append("AAA水果批发");
    passward.append("123456");
    username.append("贞德食泥鸭");
    passward.append("123456");
    //初始化聊天室
    chatname.append("交流群1");
    chatname.append("待定");
    chatname.append("待定");
    //通过resize设置二维数组的行和列
    chatnumber.resize(3); //3行即设置3个聊天室
        for(int j=0;j<chatnumber.size();j++)
        {
            chatnumber[j].resize(10); //每个聊天室最多10人
        }

        //通过遍历赋值,初始化序号9999
            for(int i = 0; i < chatnumber.size(); i++)
            {
               for (int  j= 0; j < chatnumber[0].size();j++)
                {
                    chatnumber[i][j]=9999;
                }
            }

        for(int j=0;j<chatnumber.size();j++) //记录目前连接数
        {
            now.append(0);
        }

    for(int i=0;i<username.length();i++){
        QString fff = username[i];
        ui->record->append("初始化账号：" + fff);
        QString mmm = passward[i];
        ui->record->append("初始化密码：" + mmm);
    }

    //创建监听的服务器对象和套接字
    m_s = new QTcpServer(this);
    m_tcp = new QTcpSocket(this);
    //等待客户端连接
    connect(m_s,&QTcpServer::newConnection,this,[=](){
        m_tcp= m_s->nextPendingConnection();

        //把mtcp放入clientsocket类，方便线程处理
        //clientsocket *cs = new clientsocket(m_tcp);
        //创建线程
        //QThread *thread = new QThread(this);
        //处理cs回收,线程回收和套接字回收
        //connect(m_tcp,SIGNAL(disconnected()),cs,SLOT(deleteLater()));
        //connect(m_tcp,SIGNAL(disconnected()),thread,SLOT(quit()));
        //把cs对象移动到线程中，启动线程
        //cs->moveToThread(thread);
        //thread->start();

        //把新进来的客户端存入列表
        mytcp.append(m_tcp);
        QString ip=m_tcp->peerAddress().toString();//获取对方的ip
        quint16 port=m_tcp->peerPort();//获取对方的端口
        QString stripport = QString("[%1:%2]客户端进行连接......").arg(ip).arg(port);
        ui->record->append(stripport);

        m_status->setPixmap(QPixmap(":/C:/client_logo/tick 1.png").scaled(45,45));       

        //检测是否可以接受客户端数据
        connect(m_tcp,&QTcpSocket::readyRead,this,[=](){

            QByteArray buffer;

            //利用for循环循环列表中的每一个连接进来的客户端，判断是哪一个客户端发的数据
            for(int i=0;i<mytcp.length();i++)
            {
                m_tcp = mytcp.at(i);
                buffer = m_tcp->readAll();

                QString ip1=m_tcp->peerAddress().toString();//获取对方的ip
                quint16 port1=m_tcp->peerPort();//获取对方的端口
                QString stripport1 = QString("客户端[%1:%2]").arg(ip1).arg(port1);

                //如果检测到接收到的数据长度不为0，则代表是这个客户端发送的数据
                if(buffer.length()!=0)
                {

                    QByteArray data1 = buffer;
                    QString data = data1;

                    //分割字符串为源昵称，目标昵称
                    if(data.contains("#",Qt::CaseSensitive))
                    {
                        QStringList list = data.split('#');

                        int flag1 =1;

                        for(int j =0;j<linkuser.length();j++)
                        {
                            if(linkuser[j]==list[0])
                            {
                                flag1=0;
                                number[j] = i; //重置昵称来源的套接字序号,对应的目的昵称
                                desuser[j]=list[1];

                                //记录接入群的成员套接字序号
                                int flag2 =0;
                                for(int kk=0;kk<chatname.length();kk++)
                                {
                                    if(list[1]==chatname[kk])
                                    {
                                        for(int ii=0 ; ii<chatnumber[0].size(); ii++)
                                        {
                                            if(chatnumber[kk][ii]==i) flag2=1;
                                        }
                                        if(flag2 == 0)
                                        {
                                            chatnumber[kk][now[kk]]=i;
                                            now[kk]=now[kk]+1;
                                        }

                                    }
                                }
                            }
                        }
                        if(flag1 == 1)
                        {
                            //记录昵称和昵称来源的套接字序号,对应的目的昵称，及linkuser[0]对应number[0]对应desuser[0]
                            linkuser.append(list[0]);
                            number.append(i);
                            desuser.append(list[1]);
                            //记录接入群的成员套接字序号
                            int flag2 =0;
                            for(int kk=0;kk<chatname.length();kk++)
                            {
                                if(list[1]==chatname[kk])
                                {
                                    for(int ii=0 ; ii<chatnumber[0].size(); ii++)
                                    {
                                        if(chatnumber[kk][ii]==i) flag2=1;
                                    }
                                    if(flag2 == 0)
                                    {
                                        chatnumber[kk][now[kk]]=i;
                                        now[kk]=now[kk]+1;
                                    }

                                }
                            }
                        }

                    }
                    ui->record->append(stripport1 + "：" + buffer);

                    int flag3 = 0; //flag3为1时为一对一聊天
                     //服务器给目的昵称转发信息,先找到原套接字序号，就知道目的昵称，再根据昵称找对应的套接字序号
                    for(int j =0;j<linkuser.length();j++)
                    {
                        if(number[j]==i)
                        {
                            //给一对一转发
                            for(int k =0;k<linkuser.length();k++)
                            {
                                if(linkuser[k]==desuser[j])
                                {
                                    desnumber = k;
                                    flag3 = 1;
                                    bool issend = true;
                                    if(desnumber!=9999)
                                    {
                                        QString fromuser;
                                        fromuser = linkuser[j];
                                        QString useranddata2 =  "用户 '"+fromuser+"' say："+data;
                                        for(int t=0;t<linkuser.length();t++)
                                        {
                                            QString str2 = linkuser[t]+"#";
                                            if(data.contains(str2,Qt::CaseSensitive))
                                            {
                                                //issend判断是否转发连接信息 原昵称#目的昵称 ,false为不转发
                                                issend = false;
                                                //转发验证信息
                                                QString str5 = "用户 '"+fromuser+"' "+"已连接";
                                                mytcp[number[desnumber]]->write(str5.toUtf8());
                                                QString str6 = "用户 '"+desuser[j]+"' "+"已连接";
                                                mytcp[number[j]]->write(str6.toUtf8());
                                            }
                                        }
                                        if(issend == true)
                                        {
                                            mytcp[number[desnumber]]->write(useranddata2.toUtf8());
                                            ui->record->append("已转发 '"+linkuser[desnumber]+" '"+data);
                                        }

                                    }
                                }
                            }
                            //聊天室群发
                            if(flag3 == 0)
                            {
                                for(int jj=0;jj<chatname.length();jj++)
                                {
                                    if(desuser[j]==chatname[jj])
                                    {
                                        QString fromuser2;
                                        fromuser2 = linkuser[j];

                                        QString useranddata1 =  "用户 '"+fromuser2+"' say："+data;
                                        for(int x=0;x<now[jj];x++)
                                        {
                                            //转发除了自己外的群成员
                                            if(chatnumber[jj][x]!=i)
                                            {
                                                //issend判断是否转发连接信息 原昵称#目的昵称 ,false为不转发
                                                bool issend2 = true;
                                                for(int t=0;t<linkuser.length();t++)
                                                {
                                                    QString str3 = linkuser[t]+"#";
                                                    if(data.contains(str3,Qt::CaseSensitive))
                                                    {
                                                        issend2 = false;
                                                        QString str5 = "用户 '"+fromuser2+"' "+"已加入群聊";
                                                        mytcp[chatnumber[jj][x]]->write(str5.toUtf8());
                                                    }
                                                }
                                                if(issend2 == true)
                                                {
                                                    mytcp[chatnumber[jj][x]]->write(useranddata1.toUtf8());
                                                }
                                            }
                                            //发给在群中自己的验证信息
                                            if(chatnumber[jj][x]==i)
                                            {
                                                for(int t=0;t<linkuser.length();t++)
                                                {
                                                    QString str3 = linkuser[t]+"#";
                                                    if(data.contains(str3,Qt::CaseSensitive))
                                                    {
                                                        QString str5 = "您已加入群聊";
                                                        mytcp[chatnumber[jj][x]]->write(str5.toUtf8());
                                                    }
                                                }
                                            }
                                        }
                                        //issend判断是否记录连接信息 原昵称#目的昵称 ,false为不记录
                                        bool issend2 = true;
                                        for(int t=0;t<linkuser.length();t++)
                                        {
                                            QString str3 = linkuser[t]+"#";
                                            if(data.contains(str3,Qt::CaseSensitive))
                                            {
                                                issend2 = false;
                                            }
                                        }
                                        if(issend2 == true)
                                        {
                                            ui->record->append("已群发 '"+linkuser[j]+" '"+data);
                                        }
                                    }
                                }
                            }
                        }

                    }


                }

            }

            //核对账号密码
            for(int i=0;i<username.length();i++)
            {
                QString str1=username[i]+passward[i];
                if(str1 == buffer )
                {
                    ui->record->append("用户: '"+username[i]+"' 验证成功");
                    QString checkmsg = "true";
                    m_tcp->write(checkmsg.toUtf8());

                }
            }

        });

        connect(m_tcp,&QTcpSocket::disconnected,this,[=](){
            m_tcp->close();
            //m_tcp->deleteLater();
            m_status->setPixmap(QPixmap(":/C:/client_logo/error 1.png").scaled(45,45));
        });
    });
    //状态栏
    m_status=new QLabel;
    m_status->setPixmap(QPixmap(":/C:/client_logo/error 1.png").scaled(45,45));
    ui->statusBar->addWidget(new QLabel("连接状态："));
    ui->statusBar->addWidget(m_status);
}

MainWindow::~MainWindow()
{
    delete ui;
}

//启动监听
void MainWindow::on_startlisten_clicked()
{
    unsigned short port = ui->port->text().toUShort();
    if(m_s->listen(QHostAddress::Any,port))
    {
        ui->record->append(("服务器监听成功！"));
        ui->startlisten->setDisabled(true);
    }
    else {
        ui->record->append("服务器监听失败！");
    }

}

//给客户端发送数据
void MainWindow::on_sentmsg_clicked()
{
    QString msg = ui->msg->toPlainText();
    QString msg1 = "服务器：" + msg;
    for(int j = 0;j<mytcp.length();j++)
    {
        mytcp[j]->write(msg1.toUtf8());
    }
    ui->record->append("服务器：" + msg);
}
